const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
const fs = require('fs')
const AppUtil = require('./AppUtil')

function createWindow() {
  const win = new BrowserWindow({
    width: 1600,
    height: 600,
    frame: false,
    webPreferences: {
      preload: path.join(__dirname, '../preload.js'),
      nodeIntegration: true,
      enableRemoteModule: true,
      // 官网似乎说是默认false，但是这里必须设置contextIsolation
      contextIsolation: false,
      webSecurity: false, // 安全策略
      sandbox: false,
    },
  })

  require('@electron/remote/main').initialize();
  require('@electron/remote/main').enable(win.webContents);

  let pagePath = process.env.IS_DEV
    ? 'http://localhost:5173'
    : path.format({
      pathname: path.join(__dirname, '../../dist/index.html'),
      protocol: 'file:',
      slashes: true
    });
  win.loadURL(pagePath);

  if (process.env.IS_DEV) {
    win.webContents.openDevTools()
  }
  // win.maximize();
}

/**
 * 全局事件
 */
process.on('uncaughtException', function (error) {
  console.log(error);
  console.log(error.stackTrace);
});
process.on('unhandledRejection', function (err, promise) {
  console.log(err.stackTrace);
});
process.on('warning', e => {
  console.warn(e.stack);
});

app.whenReady().then(() => {

  // 初始化json配置文件
  if (!AppUtil.existsConfig()) {
    AppUtil.createConfig()
  }

  // 关闭窗体
  ipcMain.on('close-app', (event) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    if (win) {
      win.close()
    }
  })
  // 最大化窗体
  ipcMain.on('max-app', (event) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.maximize()
  })
  // 还原窗体
  ipcMain.on('unmax-app', (event) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.unmaximize()
  })
  // 最小化窗体
  ipcMain.on('min-app', (event) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.minimize()
  })

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })

  createWindow()

})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


app.AppUtil = AppUtil;